package crawler.feiyate;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zql.entity.AgencyEntity;

import util.HttpConnectionGet;
import util.MybatisTool;
import util.TianYanCha;

public class GuangQiFeiYaTeCrawler {
	public List<AgencyEntity> getAgency() throws ScriptException {
		List<AgencyEntity> list = new ArrayList<AgencyEntity>();
		//获取JSON字符串
		String getDealer = "http://www.fiat.com.cn/mobile/js/jingxiaoshang.js";
		String dealerText = HttpConnectionGet.getJson(getDealer);
		ScriptEngineManager manger = new ScriptEngineManager();
		ScriptEngine engine = manger.getEngineByName("js");
		dealerText = (String) engine.eval(dealerText + " JSON.stringify(jingxiaoshang)");
		//解析JSON字符串
		JSONArray dealers = JSON.parseArray(dealerText);
		for(int i=0;i<dealers.size();i++) {
			JSONObject dealer = dealers.getJSONObject(i);
			String name = dealer.getString("Name");
			String address = dealer.getString("DealerAddress");
			String sellTell = dealer.getString("SalesPhone");
			String province = dealer.getString("SProvince");
			String city = dealer.getString("SCity");
			String lng = dealer.getString("GFLatitude");
			String lat = dealer.getString("GFLongitude");
			List<String> shareholder = TianYanCha.getShareholder(name);
			String sControllingShareholder = shareholder.get(0);
			String sOtherShareholders = shareholder.get(1);
			
			AgencyEntity agency = new AgencyEntity();
			agency.setdCloseDate(null);
			agency.setdOpeningDate(null);
			agency.setdUpdateTime(new Timestamp(System.currentTimeMillis()));
			agency.setnBrandID(-1);
			agency.setsBrand("菲亚特");

			agency.setnDealerIDWeb(-1);
			agency.setnManufacturerID(-1);
			agency.setsManufacturer("广汽菲亚特");

			agency.setnState(1);
			agency.setsAddress(address);
			agency.setsCity(city);
			agency.setsCustomerServiceCall(null);
			agency.setsDealerName(name);
			agency.setsDealerType(null);
			agency.setsProvince(province);
			agency.setsSaleCall(sellTell);
			agency.setsLongitude(lng);
			agency.setsLatitude(lat);
			agency.setsControllingShareholder(sControllingShareholder);
			agency.setsOtherShareholders(sOtherShareholders);
			list.add(agency);
		}
		
		
		return list;
	}
	public static void main(String[] args) throws ScriptException {
		GuangQiFeiYaTeCrawler crawler = new GuangQiFeiYaTeCrawler();
		System.out.println("爬虫开始...");
		List<AgencyEntity> agencys = crawler.getAgency();
		System.out.println("抓取完毕,正在存库");
		for(AgencyEntity agency : agencys) {
			MybatisTool.save(agency);
		}
		MybatisTool.close();
		System.out.println("请查看数据库");
	}

}
